<template>
  <div>
    <h3>PiniaDemo</h3>
    <p>counterStore{{ counterStore }}</p>
    <p>name {{ name }}</p>
    <p>counter {{ counter }}</p>
    <p>tripleCounter {{ tripleCounter }}</p>
    <p>isAdmin {{ isAdmin }}</p>
    <p>items {{ items }}</p>
    <div>
      <button @click="counterStore.counter++">store.counter++</button>
      <button @click="counterStore.$reset()">store.$reset()</button>
      <button @click="doPatch">doPatch</button>
    </div>
  </div>
</template>

<script setup>
import { computed, watch,onBeforeUnmount } from "vue";
import { storeToRefs } from "pinia";
import { useCounterStore } from "@/stores/counter";

const counterStore = useCounterStore();

const { name, counter, isAdmin, items } = storeToRefs(counterStore);

const tripleCounter = computed(() => counterStore.counter * 3);

const doPatch = () => {
  counterStore.$patch((state) => {
    state.items.push({ name: "shoes", quantity: 1 });
    state.isAdmin = !state.isAdmin;
  });
};

/* 订阅store的状态变化 */
counterStore.$subscribe(
  /* store的状态变化时回调 */
  (mutation, state) => {
    console.log(
      "订阅/subscribe到counterStore的状态变化:mutation, state=",
      mutation,
      state
    );

    // 每当它发生变化时，将整个状态持久化到本地存储
    localStorage.setItem("counter", JSON.stringify(state));
  }
);

/* 使用watch侦听pinia的变化 */
const stopper = watch(
  counterStore,
  (state) => {
    // 每当它发生变化时，将整个状态持久化到本地存储
    console.log("watch到state发生了变化：state=", state);
  },
  { deep: true }
);

onBeforeUnmount(
    ()=>{
        stopper()
    }
)


</script>

<style lang="scss" scoped></style>
